package SpringMVC.第四章.NIOSocket;



import sun.net.www.protocol.jar.Handler;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

public class NIOServer {
    public static void main(String[] args) throws Exception{
        // 创建ServerSocketChannel，监听8080端口
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(8080));
        // 设置为非阻塞模式
        ssc.configureBlocking(false);
        // 为ssc注册选择器
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        // 创建处理器
//        Handler handler = new Handler(1024);
        while (true) {
            // 等待请求，每次等待阻塞3秒，超过3秒后线程继续向下执行，如果传入0或者不传参数将一直阻塞
            if(selector.select(3000) == 0) {
                System.out.println("等待请求超时......");
                continue;
            }
            System.out.println("处理请求");
            // 获取待处理的SelectionKey
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                try {
                    // 接收到连接请求时
                    if(key.isAcceptable()) {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
